package com.kedacom.demo.emailgateway.service;

import java.util.List;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.mail.MailSendException;
import org.springframework.stereotype.Service;

import com.kedacom.demo.emailgateway.core.annotation.Properties;
import com.kedacom.demo.emailgateway.dao.EmailDao;
import com.kedacom.demo.emailgateway.exception.BusinessException;
import com.kedacom.demo.emailgateway.model.EmailException;
import com.kedacom.demo.emailgateway.model.EmailHistory;
import com.kedacom.demo.emailgateway.model.UnderwayEmail;
import com.kedacom.demo.emailgateway.model.UnderwayEmailSendToManyUser;
import com.kedacom.demo.emailgateway.util.TimeUtil;

/**
 * 定时任务重新发送,重试次数最多为${maxTimes}
 * 
 * @author wengxiongfei
 * @date 2013-12-5 下午3:45:28
 * @note EmailResenderServiceImpl
 */
@Service("emailResenderService")
public class EmailResenderServiceImpl implements EmailResenderService {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	EmailDao emailDao;
	@Resource
	EmailGatewayHelper emailGatewayHelper;

	@Properties(name = "maxTimes")
	private String maxTimes;// 可以重新发送的最大次数

	private void resend() {
		List<UnderwayEmail> list = emailDao.listEmails();
		logger.debug("list.size = " + list.size());
		for (UnderwayEmail underwayEmail : list) {
			if (underwayEmail != null) {
				try {
					underwayEmail.setNum(underwayEmail.getNum() + 1);
					if (underwayEmail.getTo().split(",").length > 1) {
						UnderwayEmailSendToManyUser sendToManay = new UnderwayEmailSendToManyUser();
						BeanUtils.copyProperties(underwayEmail, sendToManay);
						emailGatewayHelper.sendMimeMailByMailSender(sendToManay);
					} else {
						emailGatewayHelper.sendMimeMailByMailSender(underwayEmail);
					}
					onSendSucess(underwayEmail);
				} catch (BusinessException be) {
					underwayEmail.setRemarks(be.getMessage());
					onSendSucess(underwayEmail);
				} catch (SendFailedException sfe) {
					onSendFailure(underwayEmail, sfe);
					logger.debug("SendFailedException = " + sfe.getMessage());
				} catch (MessagingException me) {
					onSendFailure(underwayEmail, me);
					logger.debug("MessagingException = " + me.getMessage());
				} catch (MailSendException mse) {
					onSendFailure(underwayEmail, mse);
					logger.debug("MailSendException = " + mse.getMessage());
				} catch (Exception e) {
					onSendFailure(underwayEmail, e);
					logger.debug("exception = " + e.getMessage());
				}
			}
		}
	}

	private void onSendSucess(UnderwayEmail email) {
		EmailHistory emailHistory = new EmailHistory();
		BeanUtils.copyProperties(email, emailHistory);
		emailHistory.setSendDateTime(TimeUtil.getCurrentTime());
		emailDao.saveHistoryEmail(emailHistory);
		emailDao.deleteEmail(email);
	}

	private void onSendFailure(UnderwayEmail underwayEmail, Exception e) {
		if (underwayEmail.getNum() < Integer.valueOf(maxTimes)) {
			this.updateTimes(underwayEmail);
			logger.debug("updateTimes success");
		} else {
			EmailException emailException = new EmailException();
			BeanUtils.copyProperties(underwayEmail, emailException);
			emailException.setSendDateTime(TimeUtil.getCurrentTime());
			emailException.setException(e.toString());
			emailException.setMessage(e.getMessage());
			emailDao.saveExceptionEmail(emailException);
			emailDao.deleteEmail(underwayEmail);
			logger.debug("saveExceptionEmail and deleteEmail success");
		}
	}

	private void updateTimes(UnderwayEmail underwayEmail) {
		emailDao.updateTimes(underwayEmail);
	}

	/**
	 * 定时任务执行
	 */
	public void execute() {
		try {
			this.resend();
		} catch (Exception ex) {
			logger.debug("execute Exception : " + ex.getMessage());
			ex.printStackTrace();
		}
	}
}
